package com.cyy.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.springbootinit.annotation.AuthCheck;
import com.cyy.springbootinit.common.BaseResponse;
import com.cyy.springbootinit.common.DeleteRequest;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.common.ResultUtils;
import com.cyy.springbootinit.constant.UserConstant;
import com.cyy.springbootinit.exception.BusinessException;
import com.cyy.springbootinit.exception.ThrowUtils;
import com.cyy.springbootinit.model.dto.balanceWarning.BalanceWarningAddRequest;
import com.cyy.springbootinit.model.dto.balanceWarning.BalanceWarningEditRequest;
import com.cyy.springbootinit.model.dto.balanceWarning.BalanceWarningQueryRequest;
import com.cyy.springbootinit.model.dto.balanceWarning.BalanceWarningUpdateRequest;
import com.cyy.springbootinit.model.entity.BalanceWarning;
import com.cyy.springbootinit.model.entity.User;
import com.cyy.springbootinit.model.vo.BalanceWarningVO;
import com.cyy.springbootinit.service.BalanceWarningService;
import com.cyy.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 余额预警表接口
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@RestController
@RequestMapping("/balanceWarning")
@Slf4j
public class BalanceWarningController {

    @Resource
    private BalanceWarningService balanceWarningService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建余额预警表
     *
     * @param balanceWarningAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addBalanceWarning(@RequestBody BalanceWarningAddRequest balanceWarningAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(balanceWarningAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        BalanceWarning balanceWarning = new BalanceWarning();
        BeanUtils.copyProperties(balanceWarningAddRequest, balanceWarning);
        // 数据校验
        balanceWarningService.validBalanceWarning(balanceWarning, true);
        // todo 填充默认值
        // 写入数据库
        boolean result = balanceWarningService.save(balanceWarning);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newBalanceWarningId = balanceWarning.getWarningId();
        return ResultUtils.success(newBalanceWarningId);
    }

    /**
     * 删除余额预警表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteBalanceWarning(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        BalanceWarning oldBalanceWarning = balanceWarningService.getById(id);
        ThrowUtils.throwIf(oldBalanceWarning == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        // 操作数据库
        boolean result = balanceWarningService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新余额预警表（仅管理员可用）
     *
     * @param balanceWarningUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateBalanceWarning(@RequestBody BalanceWarningUpdateRequest balanceWarningUpdateRequest) {
        if (balanceWarningUpdateRequest == null || balanceWarningUpdateRequest.getWarningId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        BalanceWarning balanceWarning = new BalanceWarning();
        BeanUtils.copyProperties(balanceWarningUpdateRequest, balanceWarning);
        // 数据校验
        balanceWarningService.validBalanceWarning(balanceWarning, false);
        // 判断是否存在
        long id = balanceWarningUpdateRequest.getWarningId();
        BalanceWarning oldBalanceWarning = balanceWarningService.getById(id);
        ThrowUtils.throwIf(oldBalanceWarning == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = balanceWarningService.updateById(balanceWarning);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取余额预警表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<BalanceWarningVO> getBalanceWarningVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        BalanceWarning balanceWarning = balanceWarningService.getById(id);
        ThrowUtils.throwIf(balanceWarning == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(balanceWarningService.getBalanceWarningVO(balanceWarning, request));
    }

    /**
     * 分页获取余额预警表列表（仅管理员可用）
     *
     * @param balanceWarningQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<BalanceWarning>> listBalanceWarningByPage(@RequestBody BalanceWarningQueryRequest balanceWarningQueryRequest) {
        long current = balanceWarningQueryRequest.getCurrent();
        long size = balanceWarningQueryRequest.getPageSize();
        // 查询数据库
        Page<BalanceWarning> balanceWarningPage = balanceWarningService.page(new Page<>(current, size),
                balanceWarningService.getQueryWrapper(balanceWarningQueryRequest));
        return ResultUtils.success(balanceWarningPage);
    }

    /**
     * 分页获取余额预警表列表（封装类）
     *
     * @param balanceWarningQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<BalanceWarningVO>> listBalanceWarningVOByPage(@RequestBody BalanceWarningQueryRequest balanceWarningQueryRequest,
                                                               HttpServletRequest request) {
        long current = balanceWarningQueryRequest.getCurrent();
        long size = balanceWarningQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<BalanceWarning> balanceWarningPage = balanceWarningService.page(new Page<>(current, size),
                balanceWarningService.getQueryWrapper(balanceWarningQueryRequest));
        // 获取封装类
        return ResultUtils.success(balanceWarningService.getBalanceWarningVOPage(balanceWarningPage, request));
    }

    /**
     * 分页获取当前登录用户创建的余额预警表列表
     *
     * @param balanceWarningQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<BalanceWarningVO>> listMyBalanceWarningVOByPage(@RequestBody BalanceWarningQueryRequest balanceWarningQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(balanceWarningQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        //balanceWarningQueryRequest.setUserId(loginUser.getId());
        long current = balanceWarningQueryRequest.getCurrent();
        long size = balanceWarningQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<BalanceWarning> balanceWarningPage = balanceWarningService.page(new Page<>(current, size),
                balanceWarningService.getQueryWrapper(balanceWarningQueryRequest));
        // 获取封装类
        return ResultUtils.success(balanceWarningService.getBalanceWarningVOPage(balanceWarningPage, request));
    }

    /**
     * 编辑余额预警表（给用户使用）
     *
     * @param balanceWarningEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editBalanceWarning(@RequestBody BalanceWarningEditRequest balanceWarningEditRequest, HttpServletRequest request) {
        if (balanceWarningEditRequest == null || balanceWarningEditRequest.getWarningId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        BalanceWarning balanceWarning = new BalanceWarning();
        BeanUtils.copyProperties(balanceWarningEditRequest, balanceWarning);
        // 数据校验
        balanceWarningService.validBalanceWarning(balanceWarning, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = balanceWarningEditRequest.getWarningId() ;
        BalanceWarning oldBalanceWarning = balanceWarningService.getById(id);
        ThrowUtils.throwIf(oldBalanceWarning == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
    /*    if (!oldBalanceWarning.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }*/
        // 操作数据库
        boolean result = balanceWarningService.updateById(balanceWarning);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
